package storage

import (
	"context"
	"fmt"
	"log"
	"sync"
	"time"

	"mcp-server/internal/qdrant"
)

// SimpleStorageClient 简化的存储客户端实现
type SimpleStorageClient struct {
	baseClient  qdrant.QdrantClient
	config      *StorageConfig
	collections map[string]*CollectionInfo
	stats       *StorageStats
	mutex       sync.RWMutex
	initialized bool
}

// NewSimpleStorageClient 创建简化存储客户端
func NewSimpleStorageClient() *SimpleStorageClient {
	return &SimpleStorageClient{
		collections: make(map[string]*CollectionInfo),
		stats: &StorageStats{
			Collections: make(map[string]*CollectionStats),
		},
	}
}

// Initialize 初始化客户端
func (sc *SimpleStorageClient) Initialize(config *StorageConfig) error {
	sc.mutex.Lock()
	defer sc.mutex.Unlock()

	if sc.initialized {
		return fmt.Errorf("客户端已初始化")
	}

	log.Println("正在初始化简化存储客户端...")

	sc.config = config

	// 创建基础Qdrant客户端
	sc.baseClient = qdrant.NewVectorClient()

	// 初始化基础客户端
	if err := sc.baseClient.Initialize(config.QdrantConfig); err != nil {
		return fmt.Errorf("初始化基础客户端失败: %w", err)
	}

	sc.initialized = true
	log.Println("简化存储客户端初始化完成")

	return nil
}

// Close 关闭客户端
func (sc *SimpleStorageClient) Close() error {
	sc.mutex.Lock()
	defer sc.mutex.Unlock()

	if !sc.initialized {
		return nil
	}

	log.Println("正在关闭简化存储客户端...")

	if sc.baseClient != nil {
		if err := sc.baseClient.Close(); err != nil {
			return fmt.Errorf("关闭基础客户端失败: %w", err)
		}
	}

	sc.initialized = false
	log.Println("简化存储客户端已关闭")

	return nil
}

// HealthCheck 健康检查
func (sc *SimpleStorageClient) HealthCheck() error {
	sc.mutex.RLock()
	defer sc.mutex.RUnlock()

	if !sc.initialized {
		return fmt.Errorf("客户端未初始化")
	}

	return sc.baseClient.HealthCheck()
}

// IsReady 检查是否就绪
func (sc *SimpleStorageClient) IsReady() bool {
	sc.mutex.RLock()
	defer sc.mutex.RUnlock()

	return sc.initialized && sc.baseClient != nil && sc.baseClient.HealthCheck() == nil
}

// CreateCollection 创建集合
func (sc *SimpleStorageClient) CreateCollection(ctx context.Context, name string, config *CollectionConfig) error {
	sc.mutex.Lock()
	defer sc.mutex.Unlock()

	if !sc.initialized {
		return fmt.Errorf("客户端未初始化")
	}

	log.Printf("正在创建集合: %s", name)

	// 检查集合是否已存在
	if _, exists := sc.collections[name]; exists {
		return fmt.Errorf("集合 %s 已存在", name)
	}

	// 检查基础客户端是否存在
	if sc.baseClient == nil {
		return fmt.Errorf("基础客户端未初始化")
	}

	// 创建基础集合
	qdrantConfig := qdrant.CollectionConfig{
		VectorSize: config.VectorSize,
		Distance:   config.Distance,
	}

	if err := sc.baseClient.CreateCollection(name, qdrantConfig); err != nil {
		return fmt.Errorf("创建基础集合失败: %w", err)
	}

	// 创建集合信息
	collectionInfo := &CollectionInfo{
		Name:         name,
		VectorCount:  0,
		VectorSize:   config.VectorSize,
		Distance:     config.Distance,
		Status:       "active",
		IndexedCount: 0,
		Config:       config,
		CreatedAt:    time.Now(),
		UpdatedAt:    time.Now(),
	}

	sc.collections[name] = collectionInfo

	// 更新统计信息
	sc.updateStats()

	log.Printf("集合 %s 创建成功", name)
	return nil
}

// DeleteCollection 删除集合
func (sc *SimpleStorageClient) DeleteCollection(ctx context.Context, name string) error {
	sc.mutex.Lock()
	defer sc.mutex.Unlock()

	if !sc.initialized {
		return fmt.Errorf("客户端未初始化")
	}

	log.Printf("正在删除集合: %s", name)

	// 检查集合是否存在
	if _, exists := sc.collections[name]; !exists {
		return fmt.Errorf("集合 %s 不存在", name)
	}

	// 删除基础集合
	if err := sc.baseClient.DeleteCollection(name); err != nil {
		return fmt.Errorf("删除基础集合失败: %w", err)
	}

	// 删除集合信息
	delete(sc.collections, name)

	// 更新统计信息
	sc.updateStats()

	log.Printf("集合 %s 删除成功", name)
	return nil
}

// GetCollectionInfo 获取集合信息
func (sc *SimpleStorageClient) GetCollectionInfo(ctx context.Context, name string) (*CollectionInfo, error) {
	sc.mutex.RLock()
	defer sc.mutex.RUnlock()

	if !sc.initialized {
		return nil, fmt.Errorf("客户端未初始化")
	}

	info, exists := sc.collections[name]
	if !exists {
		return nil, fmt.Errorf("集合 %s 不存在", name)
	}

	// 获取最新的向量计数
	baseInfo, err := sc.baseClient.GetCollectionInfo(name)
	if err == nil {
		info.VectorCount = baseInfo.VectorCount
		info.UpdatedAt = time.Now()
	}

	return info, nil
}

// ListCollections 列出所有集合
func (sc *SimpleStorageClient) ListCollections(ctx context.Context) ([]string, error) {
	sc.mutex.RLock()
	defer sc.mutex.RUnlock()

	if !sc.initialized {
		return nil, fmt.Errorf("客户端未初始化")
	}

	collections := make([]string, 0, len(sc.collections))
	for name := range sc.collections {
		collections = append(collections, name)
	}

	return collections, nil
}

// CollectionExists 检查集合是否存在
func (sc *SimpleStorageClient) CollectionExists(ctx context.Context, name string) (bool, error) {
	sc.mutex.RLock()
	defer sc.mutex.RUnlock()

	if !sc.initialized {
		return false, fmt.Errorf("客户端未初始化")
	}

	_, exists := sc.collections[name]
	return exists, nil
}

// InsertVector 插入单个向量
func (sc *SimpleStorageClient) InsertVector(ctx context.Context, collection string, vector *VectorData) error {
	return sc.InsertVectors(ctx, collection, []*VectorData{vector})
}

// InsertVectors 批量插入向量
func (sc *SimpleStorageClient) InsertVectors(ctx context.Context, collection string, vectors []*VectorData) error {
	sc.mutex.RLock()
	_, exists := sc.collections[collection]
	sc.mutex.RUnlock()

	if !exists {
		return fmt.Errorf("集合 %s 不存在", collection)
	}

	log.Printf("正在向集合 %s 插入 %d 个向量", collection, len(vectors))

	// 转换为基础向量格式
	qdrantVectors := make([]qdrant.Vector, len(vectors))
	for i, v := range vectors {
		// 设置元数据
		if v.Metadata == nil {
			v.Metadata = &VectorMetadata{
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
				Version:   1,
			}
		}

		qdrantVectors[i] = qdrant.Vector{
			ID:      v.ID,
			Vector:  v.Vector,
			Payload: v.Payload,
		}
	}

	// 插入到基础客户端
	if err := sc.baseClient.InsertVectors(qdrantVectors); err != nil {
		return fmt.Errorf("插入向量失败: %w", err)
	}

	// 更新统计信息
	sc.updateCollectionStats(collection)

	log.Printf("成功插入 %d 个向量到集合 %s", len(vectors), collection)
	return nil
}

// UpdateVector 更新向量
func (sc *SimpleStorageClient) UpdateVector(ctx context.Context, collection string, id string, vector *VectorData) error {
	sc.mutex.RLock()
	_, exists := sc.collections[collection]
	sc.mutex.RUnlock()

	if !exists {
		return fmt.Errorf("集合 %s 不存在", collection)
	}

	// 删除旧向量并插入新向量
	if err := sc.baseClient.DeleteVectors([]string{id}); err != nil {
		return fmt.Errorf("删除旧向量失败: %w", err)
	}

	// 更新元数据
	if vector.Metadata == nil {
		vector.Metadata = &VectorMetadata{}
	}
	vector.Metadata.UpdatedAt = time.Now()
	vector.Metadata.Version++

	qdrantVector := qdrant.Vector{
		ID:      vector.ID,
		Vector:  vector.Vector,
		Payload: vector.Payload,
	}

	if err := sc.baseClient.InsertVectors([]qdrant.Vector{qdrantVector}); err != nil {
		return fmt.Errorf("插入新向量失败: %w", err)
	}

	log.Printf("向量 %s 更新成功", id)
	return nil
}

// DeleteVector 删除单个向量
func (sc *SimpleStorageClient) DeleteVector(ctx context.Context, collection string, id string) error {
	return sc.DeleteVectors(ctx, collection, []string{id})
}

// DeleteVectors 批量删除向量
func (sc *SimpleStorageClient) DeleteVectors(ctx context.Context, collection string, ids []string) error {
	sc.mutex.RLock()
	_, exists := sc.collections[collection]
	sc.mutex.RUnlock()

	if !exists {
		return fmt.Errorf("集合 %s 不存在", collection)
	}

	log.Printf("正在从集合 %s 删除 %d 个向量", collection, len(ids))

	// 从基础客户端删除
	if err := sc.baseClient.DeleteVectors(ids); err != nil {
		return fmt.Errorf("删除向量失败: %w", err)
	}

	// 更新统计信息
	sc.updateCollectionStats(collection)

	log.Printf("成功删除 %d 个向量", len(ids))
	return nil
}

// GetVector 获取向量
func (sc *SimpleStorageClient) GetVector(ctx context.Context, collection string, id string) (*VectorData, error) {
	sc.mutex.RLock()
	_, exists := sc.collections[collection]
	sc.mutex.RUnlock()

	if !exists {
		return nil, fmt.Errorf("集合 %s 不存在", collection)
	}

	// 简化实现：返回基本向量数据
	return &VectorData{
		ID: id,
		Metadata: &VectorMetadata{
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
			Version:   1,
		},
	}, nil
}

// SearchVectors 搜索向量
func (sc *SimpleStorageClient) SearchVectors(ctx context.Context, collection string, query *SearchQuery) (*SearchResult, error) {
	startTime := time.Now()

	sc.mutex.RLock()
	_, exists := sc.collections[collection]
	sc.mutex.RUnlock()

	if !exists {
		return nil, fmt.Errorf("集合 %s 不存在", collection)
	}

	// 构建查询向量
	queryVector := qdrant.Vector{
		Vector: query.Vector,
	}

	// 执行搜索
	results, err := sc.baseClient.SearchVectors(queryVector, query.Limit)
	if err != nil {
		return nil, fmt.Errorf("搜索失败: %w", err)
	}

	// 转换结果
	hits := make([]*SearchHit, 0, len(results))
	for _, result := range results {
		if result.Score >= query.Threshold {
			hit := &SearchHit{
				ID:      result.ID,
				Score:   result.Score,
				Payload: result.Payload,
			}

			hits = append(hits, hit)
		}
	}

	// 应用偏移量
	if query.Offset > 0 && query.Offset < len(hits) {
		hits = hits[query.Offset:]
	}

	searchResult := &SearchResult{
		Hits:      hits,
		Total:     int64(len(hits)),
		QueryTime: time.Since(startTime),
	}

	// 更新搜索统计
	sc.updateSearchStats(collection, time.Since(startTime))

	return searchResult, nil
}

// SearchSimilar 搜索相似向量
func (sc *SimpleStorageClient) SearchSimilar(ctx context.Context, collection string, vector []float32, limit int, threshold float32) (*SearchResult, error) {
	query := &SearchQuery{
		Vector:      vector,
		Limit:       limit,
		Threshold:   threshold,
		WithPayload: true,
		WithVector:  false,
	}

	return sc.SearchVectors(ctx, collection, query)
}

// 简化的索引管理方法

// CreateIndex 创建索引
func (sc *SimpleStorageClient) CreateIndex(ctx context.Context, collection string, config *IndexConfig) error {
	log.Printf("创建索引 %s (简化实现)", config.Name)
	return nil
}

// DeleteIndex 删除索引
func (sc *SimpleStorageClient) DeleteIndex(ctx context.Context, collection string, indexName string) error {
	log.Printf("删除索引 %s (简化实现)", indexName)
	return nil
}

// GetIndexInfo 获取索引信息
func (sc *SimpleStorageClient) GetIndexInfo(ctx context.Context, collection string) ([]*IndexInfo, error) {
	return []*IndexInfo{}, nil
}

// OptimizeIndex 优化索引
func (sc *SimpleStorageClient) OptimizeIndex(ctx context.Context, collection string) error {
	log.Printf("优化集合 %s 索引 (简化实现)", collection)
	return nil
}

// 简化的批量操作方法

// BatchInsert 批量插入
func (sc *SimpleStorageClient) BatchInsert(ctx context.Context, collection string, vectors []*VectorData, batchSize int) (*BatchResult, error) {
	startTime := time.Now()
	result := &BatchResult{
		Total: len(vectors),
	}

	// 分批处理
	for i := 0; i < len(vectors); i += batchSize {
		end := i + batchSize
		if end > len(vectors) {
			end = len(vectors)
		}

		batch := vectors[i:end]
		if err := sc.InsertVectors(ctx, collection, batch); err != nil {
			result.Failed += len(batch)
			result.Errors = append(result.Errors, fmt.Sprintf("批次 %d-%d: %v", i, end-1, err))
		} else {
			result.Successful += len(batch)
		}
	}

	result.ProcessTime = time.Since(startTime)
	return result, nil
}

// BatchUpdate 批量更新
func (sc *SimpleStorageClient) BatchUpdate(ctx context.Context, collection string, updates []*VectorUpdate, batchSize int) (*BatchResult, error) {
	startTime := time.Now()
	result := &BatchResult{
		Total: len(updates),
	}

	// 分批处理
	for i := 0; i < len(updates); i += batchSize {
		end := i + batchSize
		if end > len(updates) {
			end = len(updates)
		}

		batch := updates[i:end]
		for _, update := range batch {
			vector := &VectorData{
				ID:      update.ID,
				Vector:  update.Vector,
				Payload: update.Payload,
			}

			if err := sc.UpdateVector(ctx, collection, update.ID, vector); err != nil {
				result.Failed++
				result.Errors = append(result.Errors, fmt.Sprintf("更新 %s: %v", update.ID, err))
			} else {
				result.Successful++
			}
		}
	}

	result.ProcessTime = time.Since(startTime)
	return result, nil
}

// BatchDelete 批量删除
func (sc *SimpleStorageClient) BatchDelete(ctx context.Context, collection string, ids []string, batchSize int) (*BatchResult, error) {
	startTime := time.Now()
	result := &BatchResult{
		Total: len(ids),
	}

	// 分批处理
	for i := 0; i < len(ids); i += batchSize {
		end := i + batchSize
		if end > len(ids) {
			end = len(ids)
		}

		batch := ids[i:end]
		if err := sc.DeleteVectors(ctx, collection, batch); err != nil {
			result.Failed += len(batch)
			result.Errors = append(result.Errors, fmt.Sprintf("批次 %d-%d: %v", i, end-1, err))
		} else {
			result.Successful += len(batch)
		}
	}

	result.ProcessTime = time.Since(startTime)
	return result, nil
}

// GetStorageStats 获取存储统计
func (sc *SimpleStorageClient) GetStorageStats(ctx context.Context) (*StorageStats, error) {
	sc.mutex.RLock()
	defer sc.mutex.RUnlock()

	if !sc.initialized {
		return nil, fmt.Errorf("客户端未初始化")
	}

	// 更新统计信息
	sc.updateStats()

	return sc.stats, nil
}

// GetCollectionStats 获取集合统计
func (sc *SimpleStorageClient) GetCollectionStats(ctx context.Context, collection string) (*CollectionStats, error) {
	sc.mutex.RLock()
	defer sc.mutex.RUnlock()

	if !sc.initialized {
		return nil, fmt.Errorf("客户端未初始化")
	}

	// 检查集合是否存在
	if _, exists := sc.collections[collection]; !exists {
		return nil, fmt.Errorf("集合 %s 不存在", collection)
	}

	stats, exists := sc.stats.Collections[collection]
	if !exists {
		return &CollectionStats{
			Name: collection,
		}, nil
	}

	return stats, nil
}

// 辅助方法

// updateStats 更新统计信息
func (sc *SimpleStorageClient) updateStats() {
	sc.stats.TotalCollections = int64(len(sc.collections))

	var totalVectors int64
	for name, collection := range sc.collections {
		totalVectors += collection.VectorCount

		if sc.stats.Collections[name] == nil {
			sc.stats.Collections[name] = &CollectionStats{}
		}
		sc.stats.Collections[name].VectorCount = collection.VectorCount
		sc.stats.Collections[name].LastUpdated = time.Now()
	}

	sc.stats.TotalVectors = totalVectors
}

// updateCollectionStats 更新集合统计
func (sc *SimpleStorageClient) updateCollectionStats(collection string) {
	if sc.stats.Collections[collection] == nil {
		sc.stats.Collections[collection] = &CollectionStats{
			Name: collection,
		}
	}

	// 获取最新的向量计数
	if info, err := sc.baseClient.GetCollectionInfo(collection); err == nil {
		sc.stats.Collections[collection].VectorCount = info.VectorCount
	}
	sc.stats.Collections[collection].LastUpdated = time.Now()
}

// updateSearchStats 更新搜索统计
func (sc *SimpleStorageClient) updateSearchStats(collection string, queryTime time.Duration) {
	if sc.stats.Collections[collection] == nil {
		sc.stats.Collections[collection] = &CollectionStats{
			Name: collection,
		}
	}

	stats := sc.stats.Collections[collection]
	stats.QueryCount++

	// 计算平均查询时间
	if stats.QueryCount == 1 {
		stats.AvgQueryTime = float64(queryTime.Milliseconds())
	} else {
		stats.AvgQueryTime = (stats.AvgQueryTime*float64(stats.QueryCount-1) + float64(queryTime.Milliseconds())) / float64(stats.QueryCount)
	}
}
